<?php

namespace StudyBuddy;

/**
 * Class for encapsulating
 * the callback function that will be used
 * by the Cache object when value of $key
 * not found in cache
 *
 */
class CacheCallback {

    protected $func;

    /**
     * 
     * Constructor
     * 
     * @param function $func function. Could be Closure
     * Must accept 2 params: Registry as first argument and optional $key
     * as second
     * 
     * @throws \InvalidArgumentException if not a callable function
     * 
     */
    public function __construct($func) {
        if (!\is_callable($func)) {
            throw new \InvalidArgumentException('param $func must be a callable function. Was: ' . gettype($func));
        }

        $this->func = $func;
    }

    /**
     * This method is invoked from the Cache object
     *
     *
     * @param Registry $oRegistry
     * @param string $key
     */
    public function run(\StudyBuddy\Registry $oRegistry, $key = null) {
        if (!empty($key) && !is_string($key)) {
            throw new \InvalidArgumentException('Param $key must be a key. Was: ' . gettype($key));
        }

        return $this->func($oRegistry, $key);
    }

}
